package org.vectrics.common.utils;


import org.vectrics.VectricsException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.*;

/**
 * @author mmoore
 */
public class NetUtils {
	private static Category log = Category.getInstance(NetUtils.class); 

	public static void saveHtmlPageToFile(String ipAddress, String fileName, boolean asynchronous) throws VectricsException {
		if (asynchronous == false) {
			saveHtmlPageToFile(ipAddress, fileName);
		} 
		else {
			Thread thread = new Thread(new SaveHtmlPageRunnable(ipAddress, fileName));
			thread.start();			
		}
	}
	
	public static void saveHtmlPageToFile(String ipAddress, String fileName) throws VectricsException {  
		try { 
			if (log.isDebugEnabled()) {
				log.debug("execute() - ip address: " + ipAddress);
				log.debug("execute() - file name: " + fileName);
			}
			URL url = new URL(ipAddress);
			log.debug("saveHtmlPageToFile() - reading url stream...");
			InputStream inputStream = null;
			try {
				inputStream = url.openStream();
			}
			catch (IOException iox) {
				log.error("IOException getting web content from URL: " + url.getPath());
				throw new VectricsException("IOException getting web content from URL: " + url.getPath());
			
			}
			log.debug("saveHtmlPageToFile) - got html from url, opening output file");
			
			
			FileOutputStream fileStream = null;
			try {
				fileStream = new FileOutputStream(fileName);
			}
			catch (java.io.IOException iex) {
				log.error("IOException opening file: " + fileName);
				fileStream = null;
				throw new VectricsException("IOException opening file: " + fileName);
			}
			log.debug("saveHtmlPageToFile() - reading from html stream");
			boolean done = false;
			int count = 0;
			try {
				while (!done) {
					int c = inputStream.read();
					if (c >= 0) {
						fileStream.write(c);
						count++;
					}
					else {
						done = true;
					}
				}
			}
			catch (java.io.IOException ie) {
				log.error("IOException while writing file: " + fileName);
				throw new VectricsException("IOException while writing file: " + fileName);
			}
			log.debug("execute() - reading from html stream - DONE");
			if (log.isDebugEnabled()) {
				log.debug("execute() - # bytes: " + count);
			}
						 	
		}
		catch (MalformedURLException me) {
			log.error("MalformedURLException while acquiring page: " + ipAddress, me);
			throw new VectricsException("MalformedURLException while acquiring page: " + ipAddress, me);
		}
	}
}
